<template>
  <div>
    <div ref="echarts" :style="style"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  data() {
    return {
      example: null,
    };
  },
  props: {
    options: {
      type: Object,
      default: () => {},
    },
    height: {
      type: String,
      default: '100%',
    },
    width: {
      type: String,
      default: '100%',
    },
  },
  watch: {
    options: {
      handler() {
        if (this.example) {
          if (this.options) {
            this.example.clear();
            this.example.setOption(this.options, true);
          } else {
            this.example.clear(); // 清空画布
          }
        }
      },
      deep: true,
    },
    width() {
      if (this.example) {
        this.example.resize();
      }
    },
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
      };
    },
  },
  mounted() {
    this.drawChart();
  },
  methods: {
    drawChart() {
      this.example = echarts.init(this.$refs.echarts);
      this.example.setOption(this.options, true);
      this.example.on('legendselectchanged', (params) => {
        this.$emit('legendselectchanged', params.selected);
      });
    },
  },
};
</script>
<style lang="less" scoped></style>
